package com.example.mapstuct.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.mapstruct.Named;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Lisicheng
 */
@Component
@Named("ConvertUtil")
public class ConvertUtil {

    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

    @Named("toJsonStr")
    public String toJsonStr(Object o) {
        return JSONObject.toJSONString(o);
    }

    @Named("toTrim")
    public String toTrim(String str) {

        if (str == null) {
            return null;
        }

        return str.trim();
    }

    @Named("toMap")
    public Map<String, Object> toMap(Object o) {

        if (o == null) {
            return Collections.emptyMap();
        }

        return JSON.parseObject(JSON.toJSONString(o), new TypeReference<Map<String, Object>>() {
        });
    }

    @Named("toStrByJoin")
    public <T> String toStrByJoin(List<T> list) {
        return list.stream().map(String::valueOf).collect(Collectors.joining(","));
    }

    @Named("strSplit")
    public List<String> strSplit(String str){
        if (str == null){
            return null;
        }

        return Arrays.stream(str.split(",")).collect(Collectors.toList());
    }

    @Named("strToLocalDateTime")
    public LocalDateTime strToLocalDateTime(String time) {
        return LocalDateTime.parse(time, dateTimeFormatter);
    }

    @Named("localDateTimeToStr")
    public String localDateTimeToStr(LocalDateTime localDateTime) {
        return dateTimeFormatter.format(localDateTime);
    }

    @Named("intToStr")
    public String intToStr(Integer integer) {

        if (integer == null) {
            return null;
        }

        return integer.toString();
    }

    @Named("longToStr")
    public String longToStr(Long l) {

        if (l == null) {
            return null;
        }

        return l.toString();
    }
}
